package com.flame.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.uadetector.ReadableUserAgent;
import net.sf.uadetector.UserAgentStringParser;
import net.sf.uadetector.service.UADetectorServiceFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

public final class HttpUtils {

    private HttpUtils() {
    }

    public static void writeFile(HttpServletResponse response, File file, String fileFullName) {
        try {
            String respFileName = file.getName();
            if (StringUtils.hasText(fileFullName)) {
                respFileName = fileFullName;
            }
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response
                .addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(respFileName, "UTF-8"));

            FileInputStream inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(HttpServletResponse response, String fileFullName, String fileLocation, boolean flag) {
        File file = new File(fileLocation);
        writeFile(response, file, fileFullName);
        if (flag) {
            file.delete();
        }
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    public static String getAddress(String ip) {
        if (ip.startsWith("127")) {
            return "本地局域网";
        }

        String address = "";
        try {
            String url = String.format("http://opendata.baidu.com/api.php?query=%s&co=&resource_id=6006&oe=utf8", ip);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class);
            if (resp.getStatusCode().is2xxSuccessful()) {
                String data = resp.getBody();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readValue(data, JsonNode.class);
                Iterator<JsonNode> iterator = jsonNode.get("data").iterator();
                while (iterator.hasNext()) {
                    JsonNode node = iterator.next();
                    address = node.get("location").asText();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return address;
    }

    public static String[] getBrowserInfoAndOperatingSystemInfo(String userAgent) {
        UserAgentStringParser parser = UADetectorServiceFactory.getResourceModuleParser();
        ReadableUserAgent agent = parser.parse(userAgent);
        String browserInfo = agent.getName() + " " + agent.getVersionNumber().toVersionString();
        String operatingSystemInfo = agent.getOperatingSystem().getName() + " " +
            agent.getOperatingSystem().getVersionNumber().toVersionString();
        return new String[]{browserInfo, operatingSystemInfo};
    }
}
